using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MMM.Core.Domain;
using ServiceStack.ServiceHost;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using MMM.Services.Base;
using MMM.Services.Operations;
using MMM.Services.Type;
using MMM.Services.Response;
using ServiceStack.ServiceInterface;
using MMM.Core;

namespace MMM.Services
{

    public class DepartmentService : BaseService<Department>
    {
    }
    public class DepartMentTreeService : RestServiceBase<DepartMentTree>
    {
        IRepository<Department> dtRep = ApplicationContext.Container.GetInstance<IRepository<Department>>();
        public override object OnGet(DepartMentTree request)
        {
            var node = new DepartMentTree { id = Guid.Empty };
            AddDepartMent(node, node.id);
            return node;
        }

        private void AddDepartMent(DepartMentTree node, Guid? parentId)
        {
            var departList = dtRep.GetAll(t => t.ParentID == parentId);
            if (departList.Count() > 0)
            {
                foreach (var item in departList)
                {
                    var deNode = new DepartMentTree { id = item.Id, Dlevel = item.Dlevel, expanded = true, iconCls = "", leaf = false, level = item.Dlevel, Name = item.Name, text = item.Name, parentId = parentId, Remarks = item.Remarks };
                    node.children.Add(deNode);
                    AddDepartMent(deNode, item.Id);
                }
            }
        }

        public override object OnPost(DepartMentTree request)
        {
            if (request != null)
            {
                Department depart = new Department();
                depart.Id = request.id;
                depart.Dlevel = request.Dlevel;
                depart.Name = request.text;
                depart.ParentID = request.parentId;
                depart.Remarks = request.Remarks;

                dtRep.Update(depart);
            }
            return OperationResult<DepartMentTree>.SuccessRespose;
        }
    }

    [Serializable]
    [Route("/api/departmenttree", "GET,POST")]
    public class DepartMentTree : JsonNode<DepartMentTree>
    {
        public String Name { get; set; }
        public Guid? parentId { get; set; }
        public int Dlevel { get; set; }
        public String Remarks { get; set; }
    }
}
